package com.gastudio.SMSimple;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;


/**
 * Created by 余艾龙 on 2017/6/21.
 */
public class SMSClient {
    private static String HOST  ="127.0.0.1";
    private static int PORT =8090;
    static long counter=0;
    final  static int fire=100;//发送多少个数据过去
    static long start=0;
    public static void main(String[] args) {
        start=System.currentTimeMillis();

        IoSession session=null;
        IoConnector connector=new NioSocketConnector();
        //设置超时时间
        connector.setConnectTimeoutMillis(3000);
        //设置过滤器,主要设置自定义协议的编解码
        connector.getFilterChain().addLast("codec",new ProtocolCodecFilter(new com.gastudio.Protocol.ProtocolFactory(Charset.forName("UTF-8"))));
        //connector.getFilterChain().addFirst("filter",new MyClientFilter());
        connector.getSessionConfig().setReadBufferSize(1024);
        connector.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE,10);
        connector.setHandler(new SMSClientHandler());
        //请求连接
        ConnectFuture future= connector.connect(new InetSocketAddress(HOST,PORT));
        // A.等待是否连接成功，相当于是转异步执行为同步执行。
        //future.awaitUninterruptibly();
        // .
        future.addListener(new IoFutureListener<ConnectFuture>() {
            @Override
            public void operationComplete(ConnectFuture connectFuture) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                IoSession session=connectFuture.getSession();
                sendData(session);
            }
        });
        System.out.println("客户端完成");
        session.getCloseFuture().awaitUninterruptibly();//等待关闭连接
        connector.dispose();
    }

    public static void sendData(IoSession session){
        SmsObject sms=null;
        for (int i = 0; i < fire ; i++) {
            String content="Mj_"+i;
            sms=new SmsObject();
            sms.setSender(1234+i);
            ProtocolPack pack=new ProtocolPack((byte) i,sms);
            session.write(pack);
            System.out.println("客户端异步发送数据："+pack);
        }
    }
}
